package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
)

var globalCookie = ""

func main() {
	http.HandleFunc(
		"/recommend",
		recommend,
	)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("error", err)
	}
}

func recommend(w http.ResponseWriter, rr *http.Request) {
	log.Println("new request")
	if ensureCookie() {
		return
	}

	headers := map[string]string{
		"Cookie": globalCookie,
	}

	client := &http.Client{
		Transport: &customTransport{
			Transport: http.DefaultTransport,
			Headers:   headers,
		},
	}
	r, e := client.Get("http://117.72.107.9:3000/recommend/songs")
	if e != nil {
		fmt.Println(e)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			if err != nil {
				fmt.Println(err)
			}
		}
	}(r.Body)

	body, _ := io.ReadAll(r.Body)
	ss := string(body)
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")                   // 允许任何页面跨域
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") // 允许的请求方法
	fmt.Fprintf(w, ss)
}

func ensureCookie() bool {
	if globalCookie == "" {
		c, done := fetchNewCookie()
		if done {
			return true
		}
		globalCookie = fetchCookie(c)
	}
	return false
}

func fetchNewCookie() (Co, bool) {
	response, err := http.Get("http://117.72.107.9:3000/register/anonimous")
	if err != nil {
		fmt.Println(err)
		return Co{}, true
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Println(err)
		}
	}(response.Body)

	body, e1 := io.ReadAll(response.Body)
	if e1 != nil {
		fmt.Println(e1)
		return Co{}, true
	}
	b := string(body)
	//fmt.Println(b)

	var c Co
	err = json.Unmarshal([]byte(b), &c)
	if err != nil {
		fmt.Println(err)
		return Co{}, true
	}
	fmt.Println(c.Cookie)
	return c, false
}

type customTransport struct {
	Transport http.RoundTripper
	Headers   map[string]string
}

func (c *customTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	// 设置全局请求头
	for key, value := range c.Headers {
		req.Header.Set(key, value)
	}
	// 使用默认的 Transport 发送请求
	return c.Transport.RoundTrip(req)
}

func fetchCookie(co Co) string {
	var ret = ""
	split := strings.Split(co.Cookie, ";")
	for _, s := range split {
		if strings.Contains(s, "MUSIC_A_T") {
			continue
		} else if strings.Contains(s, "MUSIC_A") {
			ret = s
			break
		}
	}
	fmt.Println(ret)
	return ret
}

type Co struct {
	Code       int
	UserId     int
	CreateTime int64
	Cookie     string
}
